package com.mths.server.dao;

import java.util.List;

import javax.persistence.Query;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mths.server.entity.DocumentMetaData;
import com.mths.server.entity.MetaData;

@Repository("documentMetaDAO")
@Transactional
public class DocumentMetaDAOImpl extends AbstractDAOImpl<String, DocumentMetaData> implements DocumentMetaDAO {

	@SuppressWarnings("unchecked")
	@Override
	public List<DocumentMetaData> loadByDocTypeOid(String docTypeOid) {
		String sqlStr = "select d from DocumentMetaData d where d.documentType.objid = :documentTypeOid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("documentTypeOid", docTypeOid);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MetaData> loadMetaDataByDocTypeOid(String docTypeOid) {
		String sqlStr = "select d.metaData from DocumentMetaData d where d.documentType.objid = :documentTypeOid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("documentTypeOid", docTypeOid);
		return query.getResultList();

	}

	@SuppressWarnings("unchecked")
	@Override
	public void deleteByDocAndMeta(String docTypeOid, String metaDataOid) {
		String sqlStr = "select d from DocumentMetaData d where d.documentType.objid = :documentTypeOid and d.metaData.objid = :metaDataOid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("documentTypeOid", docTypeOid);
		query.setParameter("metaDataOid", metaDataOid);
		List<DocumentMetaData> docMetaList = query.getResultList();
		if (docMetaList != null && !docMetaList.isEmpty()) {
			getEntityManager().remove(docMetaList.get(0));
		}
	}

	@Override
	public List<MetaData> loadMetaWithParamByDocTypeOid(String docTypeOid) {
		String sqlStr = "select d.metaData from DocumentMetaData d where d.documentType.objid = :documentTypeOid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("documentTypeOid", docTypeOid);
		List<MetaData> metaDataList = query.getResultList();
		if (metaDataList != null) {
			for (MetaData metaData : metaDataList) {
				if (metaData.getMetaDataParamList() != null && !metaData.getMetaDataParamList().isEmpty())
					Hibernate.initialize(metaData.getMetaDataParamList());
			}
		}
		return metaDataList;
	}
}
